'use strict'

const crypto = require('crypto');
var WANTU = require('./wantu.js');
var wantu = new WANTU('23246224', 'c1253bd619fad8ea02d68c283debdf2a');  //填入ak，sk
var namespace = "morefun";   //填写空间名
module.exports = function (table, sequelize) {
    var aesutil = {};
    console.log('11111111111111111111111111111111');
    /**
     * aes加密
     * @param data 待加密内容
     * @param key 必须为32位私钥
     * @returns {string}
     */
     aesutil.encryption = function (data, key, iv) {
        if (!data || data == 'null') {
            return "";
        }
        var algorithm = 'aes-128-cbc';
        var clearEncoding = 'utf8';
        var cipherEncoding = 'base64';
        var cipher = crypto.createCipheriv(algorithm, key, iv);

        var cipherChunks = [];
        cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
        cipherChunks.push(cipher.final(cipherEncoding));
        return cipherChunks.join('');
    }

    /**
     * aes解密
     * @param data 待解密内容
     * @param key 必须为32位私钥
     * @returns {string}
     */
     aesutil.decryption = function (data, key, iv) {
        if (!data || data == 'null') {
            return "";
        }
        console.log('Original cleartext: ' + data);
        var algorithm = 'aes-128-cbc';
        var clearEncoding = 'utf8';
        var cipherEncoding = 'base64';

        var cipherChunks = data;

        var decipher = crypto.createDecipheriv(algorithm, key, iv);
        var plainChunks = [];
        plainChunks.push(decipher.update(cipherChunks, cipherEncoding, clearEncoding));
        plainChunks.push(decipher.final(clearEncoding));
        return plainChunks.join('');
    }

    /*    //加密
     function encodeMixnick(str){
     console.log('** encode **');
     console.log(str);
     var key = '751f620ea5c8f930';
     var iv = '2624750004598718';
     str = aesutil.encryption(str,key,iv);
     console.log(str);
     console.log('*****');
     return str;
     }

     //解密
     function decodeMixnick(str){
     console.log('** decode **');
     console.log(str);
     var key = '751f620ea5c8f930';
     var iv = '2624750004598718';
     try{
     str = aesutil.decryption(str,key,iv);
     }catch(e){
     return '';
     }
     console.log(str);
     console.log('*****');
     return str;
 }*/

 var sender = {
        'insert': function (options) {//添加
            var options = options || {};
            return new Promise((resolve, reject) => {
                table.ww77sender.sync({force: false}).then(() => {
                    return table.ww77sender.create({
                        nickname: options.nickname,
                        imghead: options.imghead,
                        keywords: options.keywords || '',
                        message: options.message || ''
                    }).then(data => {
                        resolve(data.dataValues);
                    }).catch(err => {
                        console.log('err:', err);
                        resolve(false);
                    });
                })

            });
        },
        'getBykeywords': function (keywords) {//获取淡定
            return new Promise((resolve, reject) => {
                table.ww77sender.findAll({
                    attributes: ['nickname', 'imghead', 'message'],
                    where: {
                        'keywords': keywords
                    },
                    order: [
                    ['createdAt', 'DESC']
                    ]
                }).then(function (data) {
                    if (data != null) {
                        return resolve(data);
                    } else {
                        return resolve(null);
                    }
                }).catch((err) => {
                    console.log('err:', err);
                    return resolve(false);
                });
            });
        },
        /*       'count':function(iteamid){//获取团队成员
         return new Promise((resolve,reject)=>{
         table.ww77sender.count({
         where:{
         'iteam_id':iteamid
         },
         order:[
         ['createdAt','DESC']
         ]
         }).then(function(data){
         if(data!=null){
         return resolve(data);
         }else{
         return resolve(null);
         }
         }).catch((err)=>{
         console.log('err:',err);
         return resolve(false);
         });
         });
     }*/
 };
/* var base64Moudle = {
    https :  require('https'),
    fs :  require('fs'),
    uuid : require('node-uuid'),
    base64Img:function(url,callback){
        base64Moudle.https.get(url,function(res){
            　　var chunks = []; //用于保存网络请求不断加载传输的缓冲数据
            　　var size = 0;　　 //保存缓冲数据的总长度

            　　res.on('data',function(chunk){
            　　　　chunks.push(chunk);　    //在进行网络请求时，会不断接收到数据(数据不是一次性获取到的)，
            　　　　size += chunk.length;　　//累加缓冲数据的长度
        　　});

            　　res.on('end',function(err){
            　　　　var data = Buffer.concat(chunks, size);　　  //Buffer.concat将chunks数组中的缓冲数据拼接起来，返回一个新的Buffer对象赋值给data
            　　　　//console.log(Buffer.isBuffer(data));　　　　//可通过Buffer.isBuffer()方法判断变量是否为一个Buffer对象
            　　　　var base64Img = data.toString('base64');　　 //将Buffer对象转换为字符串并以base64编码格式显示
            callback(base64Img);
        　　});
        });
    },
    uploadImgToCDN:function(imgResult,userId,callback){
        var imagearray = [
        { 
            'featureName': 'OriginalImage',
            'imageData': imgResult.OriginalImage
        },
        {
            'featureName': imgResult.FeatureDetails[0].featureName,
            'imageData':  imgResult.FeatureDetails[0].featureImage
        },
        {
            'featureName': imgResult.FeatureDetails[1].featureName,
            'imageData':  imgResult.FeatureDetails[1].featureImage
        },
        {
            'featureName': imgResult.FeatureDetails[2].featureName,
            'imageData':  imgResult.FeatureDetails[2].featureImage
        },
        {
            'featureName': imgResult.FeatureDetails[3].featureName,
            'imageData':  imgResult.FeatureDetails[3].featureImage
        },
        {
            'featureName': imgResult.FeatureDetails[4].featureName,
            'imageData':  imgResult.FeatureDetails[4].featureImage
        },
        ];

        var btbpResultData = new Object();
        btbpResultData.status = imgResult.status;
        btbpResultData.imageKey = imgResult.imageKey;
            //btbpResultData.OriginalImage = "";
            btbpResultData.FeatureDetails = [];

            for(var i = 0; i < imgResult.FeatureDetails.length;i++ ){
              var testobj2 = {};
              testobj2.featureName = imgResult.FeatureDetails[i].featureName;
              testobj2.featureSeverity = imgResult.FeatureDetails[i].featureSeverity;
              testobj2.featureAbsoluteSeverity = imgResult.FeatureDetails[i].featureAbsoluteSeverity;

              btbpResultData.FeatureDetails.push(testobj2);
          }


          var index = 0;
          var saveData = [];

            //递归创建文件并上传至cdn
            diguicreateimg(index);

            function diguicreateimg(whichone){

              var imageName = base64Moudle.uuid.v4();
              //windows下路径
              var localPath = 'D:\\project\\ly_2\\public\\upload\\' + imageName +'.jpg';
              //linux下路径
              //var localPath = '/acs/code/public/lynxphoto/upload/' + imageName +'.jpg';

              var dataBuffer = new Buffer(imagearray[whichone].imageData,'base64');

              base64Moudle.fs.writeFile(localPath,dataBuffer,function(err){
                if(err){
                  callback(err);
              }else{
                    //console.log("文件写入成功 : " + '../public/upload/'+ imageName +'.jpg');
                    wantu.singleUpload({
                        namespace : namespace,
                        expiration : -1
                    },
                    'D:/project/ly_2/public/upload/'+ imageName +'.jpg',
                    //'/acs/code/public/lynxphoto/upload/'+ imageName +'.jpg', //linux环境下路径
                    '/floor/lynxphoto',
                    '',
                    '',
                    function(err,res){
                        //console.log("!!!err: " , err);
                        //console.log("!!!res: " , res);
                        index++;
                        if(200 == res.statusCode && index < 6){
                          var returnData = JSON.parse(res.data);
                          var saveObj = {};
                          saveObj.featureName = imagearray[whichone].featureName;
                          saveObj.imageUrl = returnData.url;
                          saveData.push(saveObj);
                          base64Moudle.fs.unlinkSync(localPath);
                          console.log("文件上传成功，并删除本地文件 : " + imagearray[whichone].featureName + " : " + imageName +'.jpg');

                          diguicreateimg(index);
                      }else if(200 == res.statusCode && index >= 6){
                          //当index = 6时，要把第五次的返回结果 塞进数据库要更新的数据，所以此处var saveObj = {};
                          var returnData = JSON.parse(res.data);
                          var saveObj = {};
                          saveObj.featureName = imagearray[whichone].featureName;
                          saveObj.imageUrl = returnData.url;
                          saveData.push(saveObj);
                          base64Moudle.fs.unlinkSync(localPath);
                          console.log("文件上传成功，并删除本地文件 : " + imagearray[whichone].featureName + " : "+ imageName +'.jpg');

                          //更新数据库
                          var updateAll = [];
                          var userUpdate;
                          userUpdate = user.updateOneById(userId,{"featureDetailsimg":JSON.stringify(saveData),"btbpResults":JSON.stringify(btbpResultData),"status":3});
                          updateAll.push(userUpdate);
                          
                          Promise.all(updateAll).then(data=>{
                              if(data[0]===false)   callback(4030);//return reply(wrapper(null,4030));//数据库异常处理

                              callback(0,saveData);//return reply(wrapper());
                          }).catch(e=>{
                              console.log(e);
                              callback(4031);
                              //return reply(wrapper(null,4031));
                          });

                      }else{
                          callback(-1);
                      }
                  }); 
                }
            });
          }

      }
  };*/
  return {
    sender: sender,
    // base64Moudle:base64Moudle
    }
}
